var express = require('express');
var router = express.Router(); //加载路由0.
var mongoose = require('mongoose');
var Goods = require('./../models/goods.js');//模型

mongoose.connect('mongodb://127.0.0.1:27017/db_demo');

mongoose.connection.on('connected',function(){
	console.log("MongoDB connected success")
});

mongoose.connection.on('error',function(){
	console.log("MongoDB connected fail")
});

mongoose.connection.on('disconnected',function(){
	console.log("MongoDB connected disconnected")
});


//查询商品列表数据
router.get('/list',function(req,res,next){
  let page = parseInt(req.param("page"));//获取页数
  let pageSize = parseInt(req.param("pageSize"));//获取每页数目
  let priceLevel = req.param("priceLevel");
  let sort = req.param("sort");//前段参数sort决定排序顺序
  let skip = (page-1)*pageSize;//索引值
  let params = {};
  var priceGt = '',priceLte = '';
  if (priceLevel!='all'){
    switch (priceLevel){
      case '0':priceGt = 0;priceLte= 100;break;
      case '1':priceGt = 100;priceLte= 500;break;
      case '2':priceGt = 500;priceLte= 1000;break;
      case '3':priceGt = 1000;priceLte= 5000;break;
     }
     params= {
       salePrice:{
         $gt:priceGt,
         $lte:priceLte
       }
     }
  }  
  let goodsModel = Goods.find(params).skip(skip).limit(pageSize);//查询所有数据,skip是跳过几条数据limit是限制
  goodsModel.sort({'salePrice':sort});//排序,sort为1正序，-1逆序
  goodsModel.exec(function(err,doc){
    if(err){
      res.json({
          status:'1',
          msg:err.message
      });//输出json文件
    }else{
      res.json({
        status:'0',
        msg:'',
        result:{
          count:doc.length,
          list:doc
        }
      })
    }
  })
});   

//加入到购物车
router.post("/addCart",function(req,res,next){
  var userId = req.cookies.userId;
  var productId = req.body.productId;
  var User = require("./../models/user.js");//获取模型
  
  User.findOne({userId:userId},function(err,userdoc){
    if(err){
      res.json({
        status:"1",
        msg:"err.message"
      })
    }else{
      if(userdoc){
        let goodsItem = "";
        userdoc.cartList.forEach(function(item){
          if(item.productId == productId){
            goodsItem = item;
            item.productNum ++;
          }
        });
        if(goodsItem){
          userdoc.save(function(err3,doc2){
                if(err3){
                  res.json({
                    status:"1",
                    msg:"err3.message"
                  })
                }else{
                  res.json({
                    status:'0',
                    msg:"",
                    result:'suc'
                  })
                }
              })
        }else{
          Goods.findOne({productId:productId},function(err2,doc){
          if(err2){
            res.json({
              status:"1",
              msg:"err2.message"
            })
          }else{
            if(doc){
              doc.productNum = 1;//向商品信息中添加两条信息
              doc.checked = 1;
              userdoc.cartList.push(doc);//将商品信息添加到User的cartList中  
              userdoc.save(function(err3,doc2){
                if(err3){
                  res.json({
                    status:"1",
                    msg:"err3.message"
                  })
                }else{
                  res.json({
                    status:'0',
                    msg:"",
                    result:'suc'
                  })
                }
              });
            }
          }
        })
        }
        
      }
    }
  })
});
 
module.exports = router;